﻿import loading.*;
dynamic class URLRequest{
	public var URL:String;
	public var onload:Function;
	public var onerror:Function;
	public var onprogress:Function;
	private var lv:LoadVars;
	private var loadpm:LoadProcessManage;
	private var eventFunObj:Object;
	private var me:URLRequest;
	public function URLRequest(urlstr:String){
		URL=urlstr;
		initVars();
	}
	public function Post(pmt:Object){
		if(URL=="" ||URL==undefined){
			say("URL 不正确["+URL+"]");
			return;
		}
		var str:String="";
		//pmt._____=(new Date()).getTime().toString();
		this.initlv();
		
		for(var p:String in pmt){
			lv[p]=pmt[p].toString();
			//str+=p+"="+pmt[p].toString()+"&";
			//trace(p + ":" + lv.p);
		}
		if(URL.indexOf("?")<0){
			str="?_____="+(new Date()).getTime().toString();
		}else{
			str="&_____="+(new Date()).getTime().toString();
		}
		trace(URL+str);
		var lvback:LoadVars = new LoadVars();
		
		lv.sendAndLoad(URL+str,lvback,"POST");
		loadpm.StartLoadTrack([lvback],null);
	}
	public function Get(pmt:Object){
		if(URL=="" ||URL==undefined){
			say("URL 不正确["+URL+"]");
			return;
		}
		pmt._____=(new Date()).getTime().toString();
		var str:String="?";
		for(var p:String in pmt){
			str+=p+"="+pmt[p].toString()+"&";
			trace("get值：["+p+"="+pmt[p]+"]");
		}
		if(str=="?") str="";
		trace(URL+str);
		this.initlv();
		lv.load(URL+str);
		loadpm.StartLoadTrack([lv],null);
	}
	private function initlv(){
		this.lv=new LoadVars();
		this.lv.me=this;
		this.lv.onLoad=this.lvOnLoadFun;
	}
	private function lvOnLoadFun(success:Boolean){
		if(!success){
			this.me.ErrorFun("load error","loaderror");
		}
	}
	private function initVars(){
		this.me=this;
		LoadProcessManage.say=this.say;
		this.eventFunObj=new Object();
		this.eventFunObj.error=ErrorFun;
		this.eventFunObj.loaded=LoadedFun;
		this.eventFunObj.progress=ProgressFun;
		this.eventFunObj.me=this;
		loadpm=new LoadProcessManage("URL请求检测");
		loadpm.addEventListener("error",this.eventFunObj);
		loadpm.addEventListener("loaded",this.eventFunObj);
		loadpm.addEventListener("progress",this.eventFunObj);
	}
	
	private function ErrorFun(msg:String , args:Object){
		if(this.me.onerror!=undefined){
			this.me.onerror(msg,args);
		}else{
			this.me.say("加载出错["+msg+"]");
		}
	}
	private function LoadedFun(msg:String , args:Object){
		if(this.me.onload!=undefined){
			this.me.onload(args[0].obj);
		}else{
			Debug.traceAllObj(args[0].obj);
		}
	}
	private function ProgressFun(msg:String , args:Object){
		say("加载数据:"+args.general.percent);
	}
	
	public function say(o:Object){
		var m:String="URLR:"+o.toString();
		trace(m);
	}
}